<?php

namespace App\Services\GameTool;

use App\Libraries\AlipaySdkPhp\AlipayFundTransToaccountTransferRequest;
use Auth;
use Route;
use Zhuzhichao\IpLocationZh\Ip;
use App\Repositories\GameTool\RedPacketRepository;
use App\Models\Enum\RedPacket;
use App\Libraries\AlipaySdkPhp\AopClient;

class RedPacketService
{
    public function __construct(RedPacketRepository $redPacketRepository)
    {
        $this->redPacketRepository = $redPacketRepository;
    }

    public function create($request)
    {
        $datas = $request->all();

        $datas['account_type'] = RedPacket::ZHI_FU_BAO;
        $datas['stat'] = RedPacket::PENDING_PAYMENT;
        $datas['stat_1_time'] = getCurrentTime();

        $result = $this->redPacketRepository->create($datas);

        return $result;
    }

    //获取全部的红包记录
    public function getAllRedPacket($request)
    {
        return $this->redPacketRepository->getAllRedPacket($request);
    }

    //同意提现
    public function agreeWithdraw($request)
    {
        $redPacket = $this->redPacketRepository->getByID($request['id']);
        $params = [
            'no' => $redPacket['no'],
            'money' => $redPacket['money'],
            'ext' => $redPacket['ext'],
        ];
        $out_biz_no = 'jf_redpacket_' . env('APP_ENV') . '_' . $request['id'];
        $payee_account = $redPacket['to_account'];
        $amount = $redPacket['money'];
        $amount = round($amount, 2);
        $payee_real_name = $redPacket['real_name'];
        $remark = '亲，剑灵世界的红包已经到账啦，感谢您的支持！';
        list($code, $msg) = self::alipay($out_biz_no, $payee_account, $amount, $payee_real_name, $remark);
        if ($code != 10000) {

            $this->redPacketRepository->update([
                'stat' => RedPacket::PAYMENT_FAILED,
                'stat_4_time' => getCurrentTime(),
                'op_id' => Auth::user()->id,
                'error_msg' => $msg,
            ], $request['id']);

            $params['time'] = time();
            $params['code'] = 400;
            $params['msg'] = '打款失败，请检查账号和名称是否匹配！';

            $callback_url = $redPacket['url'] . '?no=' . $params['no'] . '&money=' . $params['money'] . '&time=' . $params['time'] . '&ext=' . $params['ext'] . '&code=' . $params['code'] . '&msg=' . $params['msg'];
            $response = self::curl($callback_url);

            //记录日志
            $this->redPacketRepository->createLog([
                'redpacket_id' => $request['id'],
                'url' => $callback_url,
                'response' => $response,
            ]);

            return [4, $msg];
        }

        $this->redPacketRepository->update([
            'stat' => RedPacket::PAYMENT,
            'stat_2_time' => getCurrentTime(),
            'op_id' => Auth::user()->id,
        ], $request['id']);

        $params['time'] = time();
        $params['code'] = 200;
        $params['msg'] = '打款成功';
        $callback_url = $redPacket['url'] . '?no=' . $params['no'] . '&money=' . $params['money'] . '&time=' . $params['time'] . '&ext=' . $params['ext'] . '&code=' . $params['code'] . '&msg=' . $params['msg'];
        $response = self::curl($callback_url);

        //记录日志
        $this->redPacketRepository->createLog([
            'redpacket_id' => $request['id'],
            'url' => $callback_url,
            'response' => $response,
        ]);
        return [1, 'ok'];
    }

    //拒绝提现
    public function rejectWithdraw($request)
    {
        $this->redPacketRepository->update([
            'stat' => RedPacket::REJECTED,
            'stat_3_time' => getCurrentTime(),
            'op_id' => Auth::user()->id,
        ], $request['id']);

        $redPacket = $this->redPacketRepository->getByID($request['id']);

        $params = [
            'no' => $redPacket['no'],
            'money' => $redPacket['money'],
            'ext' => $redPacket['ext'],
            'time' => time(),
            'code' => 500,
            'msg' => '管理员拒绝打款',
        ];
        $callback_url = $redPacket['url'] . '?no=' . $params['no'] . '&money=' . $params['money'] . '&time=' . $params['time'] . '&ext=' . $params['ext'] . '&code=' . $params['code'] . '&msg=' . $params['msg'];
        $response = self::curl($callback_url);
        //记录日志
        $this->redPacketRepository->createLog([
            'redpacket_id' => $request['id'],
            'url' => $callback_url,
            'response' => $response,
        ]);

        return [1, 'ok'];
    }

    //支付宝打款
    private function alipay($out_biz_no, $payee_account, $amount, $payee_real_name, $remark)
    {
        $config = config('config.redpacket_alipay');
        $appid = $config["appid_game"];
        $sign_type = $config["signtype_game"];
        $app_pub_key = $config["pubkey_game"];
        $app_private_key = $config["privatekey_game"];

        $aop = new AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->apiVersion = '1.0';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $aop->signType = $sign_type;
        $aop->appId = $appid;
        $aop->rsaPrivateKey = $app_private_key;
        $aop->alipayrsaPublicKey = $app_pub_key;

        $biz_content_params = array(
            'out_biz_no' => $out_biz_no,
            'payee_type' => 'ALIPAY_LOGONID', // only support alipay_loginid
            'payee_account' => $payee_account,
            'amount' => $amount,
            'payee_real_name' => $payee_real_name,
            'remark' => $remark,
        );
        $biz_content_params = json_encode($biz_content_params);
        //AlipayFundTransToaccountTransferRequest
        $request = new AlipayFundTransToaccountTransferRequest();
        $request->setBizContent($biz_content_params);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        if (empty($result)) {
            return [-1, 'gate way接口返回为空'];
        }
        if (!isset($result->$responseNode) || empty($result->$responseNode)) {
            return [-2, $responseNode . '接口返回为空'];
        }
        if (!isset($result->$responseNode->code) || empty($result->$responseNode->code)) {
            return [-3, '支付宝接口没有返回code值'];
        }
        $resultCode = $result->$responseNode->code;
        if ($resultCode == 10000) {
            return [10000, 'ok'];
        } else {
            return [$resultCode, $result->$responseNode->msg . '-' . $result->$responseNode->sub_msg];
        }
    }

    /** php url 请求 */
    private function curl($url, $params = false, $ispost = 0, $https = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }

        $response = curl_exec($ch);
        if ($response === FALSE) {
            return false;
        }
        curl_close($ch);
        return $response;
    }
}